<?php

namespace Biz\model\activity;

use Doraemon\tools\ImgUrl;
use Biz\service\Goods;

class MiniTab extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_activity';

    const _DATABASE_ = 'shop_activity';

    const _TABLE_NAME = 'mini_tab';

    const _SUB_TABLE = false;

    // 状态为展示
    const STATUS_NORMAL = 1;
    // 状态为隐藏
    const STATUS_HIDE = 2;
    // 状态为被删除
    const STATUS_DELETE = 9;

    /**
     * @desc 获取一条有效的活动信息
     * @return mixed
     */
    public static function getActiveInfo()
    {
        $info = self::get('*', [
            'end_time[>]' => date('Y-m-d H:i:s'),
            'start_time[<]' => date('Y-m-d H:i:s'),
            'status' => self::STATUS_NORMAL,
            'ORDER' => [
                'start_time' => 'DESC'
            ]
        ]);
        if ($info) {
            return self::formatInfo($info);
        } else {
            return [];
        }
    }

    /**
     * @desc 列表
     * @param array $where
     * @return bool
     */
    public static function getList($where)
    {
        if (!isset($where['ORDER'])) {
            $where['ORDER'] = [
                'status',
                'id' => 'DESC'
            ];
        }
        $list = self::select("*", $where);
        $total = self::count('*',$where['AND']);
        if ($list) {
            foreach ($list as &$info) {
                $info = self::formatInfo($info);
            }
        }
        return compact('list', 'total');
    }

    public static function getInfoById($id)
    {
        $info = self::get("*", ['id' => $id]);
        if ($info) {
            return self::formatInfo($info);
        } else {
            return [];
        }
    }

    /**
     * @desc 添加记录
     * @param $insertData
     * @return bool
     */
    public static function addTab($insertData)
    {
        $data = [
            'status' => self::STATUS_NORMAL,
            'addtime' => date('Y-m-d H:i:s')
        ] + $insertData;
        return self::insert($data);
    }

    private static function formatInfo($info)
    {
        $info['pic_id'] = $info['pic_id'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $info['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
        return $info;
    }

    public static function saveSortInfo($sortInfo)
    {
        foreach ($sortInfo as $id => $sort) {
            self::update(['sort' => $sort], ['id' => $id]);
        }
    }

    /**
     * @desc 修改状态
     * @param $id
     * @param $status
     * @return bool
     */
    public static function changeStatusById($id, $status)
    {
        if (self::update(['status' => $status], ["id" => $id])->rowcount()) {
            return $id;
        }
    }

    /**
     * @desc 修改信息
     * @param $id
     * @param $info
     * @return bool
     */
    public static function changeInfoById($id, $info)
    {
        if (self::update($info, ["id" => $id])->rowcount()) {
            return $id;
        }
    }

}